package com.zwr.sheller.shop.service.impl;

import com.github.pagehelper.PageInfo;
import com.zwr.sheller.core.common.LSYBusinessException;
import com.zwr.sheller.core.common.LSYExceptionCode;
import com.zwr.sheller.core.pojo.Merchant;
import com.zwr.sheller.core.pojo.Seller;
import com.zwr.sheller.core.pojo.Store;
import com.zwr.sheller.core.service.impl.BaseServiceImpl;
import com.zwr.sheller.core.util.*;
import com.zwr.sheller.shop.mapper.MerchantMapper;
import com.zwr.sheller.shop.mapper.SellerMapper;
import com.zwr.sheller.shop.mapper.StoreMapper;
import com.zwr.sheller.shop.service.SellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author LSY
 * @Date 2022/1/7 8:54
 * @Version 1.0
 **/
@Service
public class SellerServiceImpl extends BaseServiceImpl<Seller> implements SellerService {

    StoreMapper storeMapper;
    MerchantMapper merchantMapper;
    SellerMapper sellerMapper;
    RedisTemplate<String, Object> template;
    ValueOperations<String, Object> stringOps;
    @Autowired(required = false)
    public SellerServiceImpl(StoreMapper storeMapper, MerchantMapper merchantMapper, SellerMapper sellerMapper, RedisTemplate<String, Object> template) {
        this.storeMapper = storeMapper;
        this.merchantMapper = merchantMapper;
        this.sellerMapper = sellerMapper;
        this.template = template;
        stringOps = template.opsForValue();
    }

    /**
     * 查找该店铺所有的管理员
     *
     * @param page
     * @param num
     * @return
     */
    @Override
    public Map<String, Object> findSellers(Integer page, Integer num) {
        temporaryThreadLocal();
        Map<String, Object> map = JsonUtil.stringToObject(String.valueOf(ThreadLocalUtil.getObject()), Map.class);

        Example example = new Example(Seller.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId", Long.parseLong(String.valueOf(map.get("storeId"))));
        PageInfo<Seller> info = this.selectTByExample(page, num, example);

        Map<String, Object> result = new HashMap<>();
        result.put("sellers", info.getList());
        result.put("count", info.getTotal());

        return result;
    }

    /**
     * 管理员、商户、店铺注册
     *
     * @param seller
     * @param merchant
     * @param store
     * @throws LSYBusinessException
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void ShellerRegister(Seller seller, Merchant merchant, Store store, String code, Boolean businessLicenseStatus, Boolean tradeLicenseStatus, Boolean idCardFrontStatus, Boolean idCardBackStatus, Boolean storeLogoStatus, Boolean storeBackgroundStatus) throws LSYBusinessException {
        validateOfCode(seller.getSellerPhone(), code);

        Example storeExample = new Example(Store.class);
        Example.Criteria storeCriteria = storeExample.createCriteria();
        storeCriteria.andEqualTo("storePhone", store.getStorePhone());

        if(storeMapper.selectByExample(storeExample).size() != 0) {
            throw new LSYBusinessException(LSYExceptionCode.DUPLICATE_STORE_PHONE);
        }
        store.setStore12hour(false);
        store.setStoreQuality(false);
        store.setStoreAddNew(false);
        store.setStoreOpenTime(new Timestamp(System.currentTimeMillis()));
        if(storeLogoStatus) {
            store.setStoreLogo("http://47.108.60.93/ossImg/" + "adminPicture" + store.getStoreLogo().substring(36));
        }
        if(storeBackgroundStatus) {
            store.setStoreBackground("http://47.108.60.93/ossImg/" + "adminPicture" + store.getStoreBackground().substring(36));
        }
        storeMapper.insertSelective(store);
        Long storeId = storeMapper.selectByExample(storeExample).get(0).getStoreId();

        Example merchantExample = new Example(Merchant.class);
        Example.Criteria merchantCriteria = merchantExample.createCriteria();
        merchantCriteria.andEqualTo("merchantPhone", merchant.getMerchantPhone());

        if(merchantMapper.selectByExample(merchantExample).size() != 0) {
            throw new LSYBusinessException(LSYExceptionCode.DUPLICATE_MERCHANT_PHONE);
        }
        merchant.setDeliveryWay(1);
        merchant.setStoreId(storeId);
        if(businessLicenseStatus) {
            merchant.setBusinessLicense("http://47.108.60.93/ossImg/" + "adminPicture" + merchant.getBusinessLicense().substring(36));
        }
        if(tradeLicenseStatus) {
            merchant.setTradeLicense("http://47.108.60.93/ossImg/" + "adminPicture" + merchant.getTradeLicense().substring(36));
        }
        if(idCardFrontStatus) {
            merchant.setIdCardFront("http://47.108.60.93/ossImg/" + "adminPicture" + merchant.getIdCardFront().substring(36));
        }
        if(idCardBackStatus) {
            merchant.setIdCardBack("http://47.108.60.93/ossImg/" + "adminPicture" + merchant.getIdCardBack().substring(36));
        }
        merchantMapper.insertSelective(merchant);
        Long merchantId = merchantMapper.selectByExample(merchantExample).get(0).getStoreId();

        sellerPhoneValidate(seller.getSellerPhone());
        seller.setSellerAccount(String.valueOf(SnowflakeUtil.nextId()));
        seller.setSellerRegTime(new Timestamp(System.currentTimeMillis()).toString());
        seller.setMerchantId(merchantId);
        seller.setStoreId(storeId);

        sellerMapper.insertSelective(seller);

        if(storeLogoStatus) {
            OSSUtil.moveFile("temporary" + store.getStoreLogo().substring(39), store.getStoreLogo().substring(27));
        }
        if(storeBackgroundStatus) {
            OSSUtil.moveFile("temporary" + store.getStoreBackground().substring(39), store.getStoreBackground().substring(27));
        }
        if(businessLicenseStatus) {
            OSSUtil.moveFile("temporary" + merchant.getBusinessLicense().substring(39), merchant.getBusinessLicense().substring(27));
        }
        if(tradeLicenseStatus) {
            OSSUtil.moveFile("temporary" + merchant.getTradeLicense().substring(39), merchant.getTradeLicense().substring(27));
        }
        if(idCardFrontStatus) {
            OSSUtil.moveFile("temporary" + merchant.getIdCardFront().substring(39), merchant.getIdCardFront().substring(27));
        }
        if(idCardBackStatus) {
            OSSUtil.moveFile("temporary" + merchant.getIdCardBack().substring(39), merchant.getIdCardBack().substring(27));
        }
    }

    /**
     * 管理员添加管理员
     *
     * @param seller
     * @throws LSYBusinessException
     */
    @Override
    public void addSeller(Seller seller) throws LSYBusinessException {
        sellerPhoneValidate(seller.getSellerPhone());

        seller.setSellerAccount(String.valueOf(SnowflakeUtil.nextId()));
        seller.setSellerRegTime(new Timestamp(System.currentTimeMillis()).toString());

        Map<String, Object> map = JsonUtil.stringToObject(String.valueOf(ThreadLocalUtil.getObject()), Map.class);
        seller.setStoreId(Long.parseLong(String.valueOf(map.get("storeId"))));
        seller.setMerchantId(Long.parseLong(String.valueOf(map.get("merchantId"))));

        sellerMapper.insertSelective(seller);
    }

    /**
     * 管理员修改账户名或邮箱接口
     *
     * @param sid
     * @param account
     * @param mail
     */
    @Override
    public void updateSeller(Long sid, String account, String mail) {
        Seller seller = new Seller();
        seller.setSellerId(sid);
        seller.setSellerAccount(account);
        seller.setSellerMail(mail);

        sellerMapper.updateByPrimaryKeySelective(seller);
    }

    /**
     * 发送短信校验码接口
     *
     * @param phone
     * @return
     */
    @Override
    public String sendSMSVerificationCode(String phone) {
        System.out.println("验证码绑定的手机号" + phone);

        String code = String.valueOf(new Random().nextInt(900000) + 100000);
        stringOps.set("SMS" + phone, code, 10, TimeUnit.MINUTES);

        return code;
    }

    @Override
    public void updateSellerPassword(String password, String code) throws LSYBusinessException {
        temporaryThreadLocal();

        Map<String, Object> information = JsonUtil.stringToObject(String.valueOf(ThreadLocalUtil.getObject()), Map.class);
        Long id = Long.parseLong(String.valueOf(information.get("sellerId")));
        String phone = String.valueOf(information.get("sellerPhone"));
        validateOfCode(phone, code);  // 调用封装的校验方法
        template.delete("SMS" + phone);  // 校验完了就删掉校验码

        Seller seller = new Seller();
        seller.setSellerId(id);
        seller.setSellerPwd(password);
        sellerMapper.updateByPrimaryKeySelective(seller);
    }

    @Override
    public void updateSellerPhone(String phone, String code) throws LSYBusinessException {
        temporaryThreadLocal();

        Map<String, Object> information = JsonUtil.stringToObject(String.valueOf(ThreadLocalUtil.getObject()), Map.class);
        Long id = Long.parseLong(String.valueOf(information.get("sellerId")));
        String oldPhone = String.valueOf(information.get("sellerPhone"));
        validateOfCode(oldPhone, code);  // 调用封装的校验方法
        template.delete("SMS" + oldPhone);  // 校验完了就删掉校验码

        Seller seller = new Seller();
        seller.setSellerId(id);
        seller.setSellerPhone(phone);
        sellerMapper.updateByPrimaryKeySelective(seller);
    }

    /**
     * 临时的ThreadLocal
     */
    private void temporaryThreadLocal() {
        Map<String, Object> map = new HashMap<>();
        map.put("storeId", 1L);
        map.put("merchantId", 1L);
        map.put("sellerId", 1L);
        map.put("sellerPhone", "13228145016");
        ThreadLocalUtil.setObject(JsonUtil.objectToString(map));
    }

    /**
     * 封装的校验手机号方法
     *
     * @param phone
     * @throws LSYBusinessException
     */
    private void sellerPhoneValidate(String phone) throws LSYBusinessException {
        if(phone == null || !RegexUtil.isPhoneNumber(phone)) {
            throw new LSYBusinessException(LSYExceptionCode.BAD_PHONE);
        }

        Example example = new Example(Seller.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sellerPhone", phone);
        if(sellerMapper.selectOneByExample(example) != null) {
            throw new LSYBusinessException(LSYExceptionCode.DUPLICATE_SELLER_PHONE);
        }
    }

    /**
     * 封装的校验验证码方法
     *
     * @param phone
     * @param code
     * @throws LSYBusinessException
     */
    private void validateOfCode(String phone, String code) throws LSYBusinessException {
        Object origin = stringOps.get("SMS" + phone);
        if (origin == null) {
            throw new LSYBusinessException(LSYExceptionCode.WRONG_PHONE);
        }

        String correct = JsonUtil.stringToObject(JsonUtil.objectToString(origin), String.class);
        if(!correct.equals(code)) {
            throw new LSYBusinessException(LSYExceptionCode.VALIDATE_FAILED);
        }
    }
}
